package com.podium.web.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.podium.auth.entity.LoginUser;
import com.podium.auth.service.TokenService;
import com.podium.auth.utils.SecurityUtils;
import com.podium.comment.AjaxResult;
import com.podium.web.log.service.SysLoginLogService;
import com.podium.web.system.controller.dto.LoginDto;
import com.podium.web.system.entity.SysMenu;
import com.podium.web.system.entity.SysUser;
import com.podium.web.system.service.LoginService;
import com.podium.web.system.service.SysMenuService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 邵文泽
 * @description 登录控制器
 * @date 2025/4/15 11:56
 */
@Slf4j
@RestController
@RequestMapping
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private TokenService tokenService;

    @Resource
    private SysMenuService menuService;

    @Autowired
    private SysLoginLogService loginLogService;

    /**
     * 获取验证码
     */
    @PreAuthorize("@preAuthorize('hasAuthority(\"system:login:verifyCode\")')")
    @GetMapping("obtainVerifyCode")
    public AjaxResult<JSONObject> verifyCode() {
        return new AjaxResult<JSONObject>().success(loginService.verifyCode());
    }

    /**
     * 登录
     */
    @PostMapping("login")
    public AjaxResult<String> login(@Validated @RequestBody LoginDto loginDto) {
        return new AjaxResult<String>().success(loginService.login(loginDto));
    }

    /**
     * 获取用户信息
     */
    @GetMapping("getUserInfo")
    public AjaxResult<SysUser> getUserInfo(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        return new AjaxResult<SysUser>().success((SysUser) loginUser.getUser());
    }

    @GetMapping("getMenuList")
    public AjaxResult<List<SysMenu>> getMenuList(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser user = (SysUser)loginUser.getUser();
        return new AjaxResult<List<SysMenu>>().success(menuService.getByUserMenus(user.getId()));
    }

    /**
     * 退出登录
     */
    @PostMapping("logout")
    public AjaxResult<Void> logout(HttpServletRequest request) {
        loginLogService.asyncEditLogoutTime(SecurityUtils.getLoginUser());
        tokenService.delLoginUser(request);
        return new AjaxResult<Void>().success();
    }

}